package com.ruoyi.third.controller;

import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.base.domain.BaseDevice;
import com.ruoyi.base.service.IBaseDeviceService;
import com.ruoyi.base.vo.VideoStream;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.manufacturer.ControlCommand;
import com.ruoyi.manufacturer.ControlVo;
import com.ruoyi.manufacturer.IPlatform;
import com.ruoyi.manufacturer.PlatformTask;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;

/**
 * 开放接口,主要是设备控制和个性化对接业务
 */
@RestController
@RequestMapping("/public/third")
@Slf4j
public class PublicController {

    @Autowired
    private IBaseDeviceService baseDeviceService;

    /**
     * 反向控制
     * @param controlVo
     */
    @PostMapping("control")
    public AjaxResult control(@RequestBody ControlVo controlVo){
        BaseDevice baseDevice = baseDeviceService.selectBaseDeviceById(controlVo.getDeviceId());
        if(baseDevice == null){
            return AjaxResult.error("设备不存在");
        }

        IPlatform handler = PlatformTask.getHandler(baseDevice.getPfCode());
        if(handler == null){
            return AjaxResult.error("未找到控制方法");
        }

        controlVo.setDevice(baseDevice);
        return handler.control(controlVo);
    }

    /**
     * 视频联动拉流
     * @param deviceId
     */
    @GetMapping("camera/{deviceId}")
    public AjaxResult camera(@PathVariable("deviceId") Long deviceId){
        BaseDevice baseDevice = baseDeviceService.selectBaseDeviceById(deviceId);
        if(baseDevice == null){
            return AjaxResult.error("设备不存在");
        }

        if(baseDevice.getPfCode() == null){
            return AjaxResult.success(new VideoStream(deviceId, baseDevice.getPosition(),"http://localhost:8088/statics/test.mp4"));
        }
        IPlatform handler = PlatformTask.getHandler(baseDevice.getPfCode());
        if(handler == null){
            return AjaxResult.error("未找到控制方法");
        }

        ControlVo controlVo = new ControlVo();
        controlVo.setCommand(ControlCommand.STREAM.getCode());
        controlVo.setDeviceId(deviceId);
        controlVo.setDevice(baseDevice);
        AjaxResult ret = handler.control(controlVo);
        VideoStream data = new VideoStream();
        data.setId(deviceId);
        data.setName(baseDevice.getPosition());
        String[] url = ret.get(AjaxResult.DATA_TAG).toString().split(",");
        if(url.length > 0){
            data.setUrl(url[0]);
        }
        if(url.length > 1){
            data.setIr(url[1]);
        }
        ret.put(AjaxResult.DATA_TAG, data);
        return ret;
    }

    /**
     * 回放视频流
     */
    @GetMapping(value = "/record/{id}")
    public AjaxResult playback(@PathVariable("id") Long id, @RequestParam(value = "name", required = false) String name,
                               @RequestParam(value = "startTime", required = false) Date startTime, @RequestParam(value = "endTime", required = false) Date endTime) {
        BaseDevice baseDevice = baseDeviceService.selectBaseDeviceById(id);
        if (baseDevice == null) {
            return AjaxResult.error("摄像机信息不存在");
        }

        IPlatform handler = PlatformTask.getHandler(baseDevice.getPfCode());
        if(handler == null){
            return AjaxResult.error("未找到控制方法");
        }

        if (name == null && startTime == null && endTime == null) {
            return AjaxResult.error("时间参数有误");
        }
        if (name == null) {
            name = DateUtils.parseDateToStr(DateUtils.YYYYMMDDHHMMSS, startTime)
                    + "_" + DateUtils.parseDateToStr(DateUtils.YYYYMMDDHHMMSS, endTime);
        }

        ControlVo controlVo = new ControlVo();
        controlVo.setCommand(ControlCommand.RECORDS.getCode());
        controlVo.setValue(name);
        controlVo.setDeviceId(id);
        controlVo.setDevice(baseDevice);
        AjaxResult ret = handler.control(controlVo);
        if (ret != null && ret.isSuccess()) {
            ret.put(AjaxResult.MSG_TAG, "查询成功");
        }
        log.info("record for {} @{}: {}", baseDevice.getCode(), name, JSONObject.toJSONString(ret));
        return ret;
    }

    /**
     * 查询录像
     */
    @GetMapping(value = "/records/{id}")
    public AjaxResult playback(@PathVariable("id") Long id, @RequestParam("day") Date day) {
        BaseDevice baseDevice = baseDeviceService.selectBaseDeviceById(id);
        if (baseDevice == null) {
            return AjaxResult.error("摄像机信息不存在");
        }


        IPlatform handler = PlatformTask.getHandler(baseDevice.getPfCode());
        if(handler == null){
            return AjaxResult.error("未找到控制方法");
        }

        ControlVo controlVo = new ControlVo();
        controlVo.setCommand(ControlCommand.RECORDS.getCode());
        controlVo.setValue(DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD, day));
        controlVo.setDeviceId(id);
        controlVo.setDevice(baseDevice);
        AjaxResult ret = handler.control(controlVo);
        if (ret != null && ret.isSuccess()) {
            ret.put(AjaxResult.MSG_TAG, "查询成功");
        }
        log.info("records for {} @{}: {}", baseDevice.getCode(), day, JSONObject.toJSONString(ret));
        return ret;
    }
}
